package com.clotingshoppos.common.util;

import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName: GlobalExceptionHandler
 * @Description: 全局异常处理
 * @Author: zhandad
 * @Date: 2019-03-21 16:15
 * @Version: v1.0
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

//    /**
//     * 系统异常处理，比如：404,500
//     * @param req
//     * @param e
//     * @return
//     * @throws Exception
//     */
//    @ExceptionHandler(value = Exception.class)
//    @ResponseBody
//    public RetResult defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
//        logger.error("", e);
//        RetResult r = new RetResult();
//        r.setMsg(e.getMessage());
//        if (e instanceof org.springframework.web.servlet.NoHandlerFoundException) {
//            r.setCode(404);
//        } else {
//            r.setCode(500);
//        }
//        r.setData(null);
//        return r;
//    }



    // 捕捉 CustomRealm 抛出的异常
    @ResponseBody
    @ExceptionHandler(AccountException.class)
    public RetResult handleShiroException(Exception ex) {
        System.out.println("im global" + ex.getMessage());

        return new RetResponse().makeErrRsp(ex.getMessage());
    }

    // 捕捉shiro的异常
    @ExceptionHandler(ShiroException.class)
    public RetResult handle401() {
        System.out.println("handle401");
        return new RetResponse().makeOKRsp().setCode(401).setMsg("您没有权限访问！");
    }

//    // 捕捉其他所有异常
//    @ExceptionHandler(Exception.class)
//    public RetResult globalException(HttpServletRequest request, Throwable ex) {
//        System.out.println("globalException");
//        return new RetResponse().makeErrRsp("访问出错，无法访问: " + ex.getMessage());
//    }

    @ExceptionHandler(UnauthenticatedException.class)
    @ResponseStatus(code = HttpStatus.UNAVAILABLE_FOR_LEGAL_REASONS,reason="服务器内部错误")
    @ResponseBody
    public RetResult unauthorizedException(Exception e) {
        logger.error("ExceptionHandler:"+e.getMessage(),e);
        return new RetResponse().makeErrRsp("token错误");
    }

}
